const { cloud, globalData } = getApp();
Page({
  data: {
    goodList: []
  },
  onLoad() {
    this.loadGood();
  },
  choose(e) {
    let idx = e.currentTarget.dataset.idx;
    let goodList = this.data.goodList;
    goodList[idx].checked = !goodList[idx].checked;
    this.setData({
      goodList: goodList
    })
  },
  async loadGood() {
    try {
      const res = await cloud.topApi.invoke({
        api: 'taobao.items.onsale.get',
        authScope: '*',
        data: { fields: 'title,pic_url,price,num_iid' }
      });
      let goodList = res.items;
      for (let i = 0; i < goodList.length; i++) {
        goodList[i].checked = false;
        goodList[i].shop_id = globalData.shop_id;
        goodList[i].product_id =  goodList[i].num_iid
      }
      this.setData({
        goodList: goodList
      })
    } catch (e) {
      my.alert({ content: 'error ' + e.message })
    }
  },
  async handleSubmit() {
    let goodList = this.data.goodList.filter(item => item.checked == true);
    for(let i=0;i<goodList.length;i++){
      goodList[i]=JSON.stringify(goodList[i])
    }
    let sendData = {
      shop_id: globalData.shop_id,
      goodList:JSON.stringify(goodList)
    };
   
    const res = await cloud.application.httpRequest({
      path: '/index.php/index/qn/writegood',
      method: 'POST',
      params: sendData
    })
     my.alert({
      content: '宝贝设置成功，返回之后再次刷新页面可以看到设置效果',
      success: (res) => {
        my.navigateTo({ url: '/pages/index/index' });
      }
    })
  }
});
